package com.library.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.library.bean.Book;
import com.library.service.BookService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.Date;

@Controller
@RequestMapping("/book")
public class BookController {

    @Resource
    private BookService bs ;

    @GetMapping("/getBooks")
    @ResponseBody
    public Object getBooks(Book book,
                           Date beginDate,
                           Date endDate,
                           @RequestParam(required = false,defaultValue = "1") int pageNum,
                            @RequestParam(required = false,defaultValue = "10") int pageSize){

        PageHelper.startPage(pageNum,pageSize);
        Page<Book> page = (Page<Book>)bs.getBooks(book, beginDate, endDate);
        return page.toPageInfo();
    }
    @RequestMapping("/insertBook")
    public String insertBook(MultipartFile b,  Book book, Model model) throws IOException {
        String o=System.currentTimeMillis()+b.getOriginalFilename();
<<<<<<< HEAD
        String rl="/test2/bImage/"+o;
        System.out.println(111111111);
        System.out.println(book);
        String rrl="c:/bImage/"+o;
        book.setBookCover("/test2/bImage/"+ o);
=======
        String rl="/test2/images/"+o;
        System.out.println(111111111);
        System.out.println(book);
        String rrl="c:/images/"+o;
        book.setBookCover("/test2/images/" + o);
>>>>>>> 1ef93dae55a044933853dfde8a8a99391a222fdb
        System.out.println(book);

        if(bs.insertBook(book)!=-1){
            b.transferTo(new File(rrl));
            model.addAttribute("msg","添加成功");
<<<<<<< HEAD
=======

        }else {
            model.addAttribute("msg","添加失败");
        }

        return "forward:/insert.jsp";
    }
>>>>>>> 1ef93dae55a044933853dfde8a8a99391a222fdb

        }else {
            model.addAttribute("msg","添加失败");
        }

        return "forward:/insert.jsp";
    }

    @PostMapping("/delete")
    @ResponseBody
    public String deleta(int bookId){
       int b= bs.deleteBook(bookId);
        if(b==1){
            return "a";
        }
        return "forward:/book.jsp";
    }
}
